package com.ruoyi.common.utils.tree;

import com.ruoyi.project.system.domain.SysDept;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@UtilityClass
public class TreeAbleUtils {
	/**
	 * 构建树形结构
	 * @param list
	 * @return
	 * @param <T>
	 */
	public <T extends TreeAble<?, T>> List<T> buildChildren(List<T> list) {
		Map<?, List<T>> pid2ChildrenMap = list.stream().collect(Collectors.groupingBy(TreeAble::getParentId));
		Set<?> idSet = list.stream().map(TreeAble::getDeptId).collect(Collectors.toSet());
		list.forEach(p -> p.setChildren(pid2ChildrenMap.get(p.getDeptId())));
		return list.stream().filter(p -> !idSet.contains(p.getParentId())).collect(Collectors.toList());
	}
}
